package config

import (
	"flag"
	"fmt"
	"gopkg.in/yaml.v3"
	"gorm.io/gorm/logger"
	"log"
	"os"
)

var (
	GlobalConfig *Config
)

func init() {

	//   配置读取
	AppConfig := flag.String("config", "app.yaml", "application config path")
	flag.Parse()
	fmt.Println("config传入的参数[默认值:app.yaml] ", *AppConfig)
	conf, _ := ConfigParse(AppConfig)
	if conf != nil {
		GlobalConfig = conf
	} else {
		log.Println("Error:config file is nil")
	}
}

type Config struct {
	Server ServerConfig `yaml:"server"`
	DB     DBConfig     `yaml:"db"`
	Redis  RedisConfig  `yaml:"redis"`
}

type ServerConfig struct {
	Env     string `yaml:"env"`
	Address string `yaml:"address"`
	Port    int    `yaml:"port"`
}

type DBConfig struct {
	Url    string `yaml:"url"`
	Prefix string `yaml:"prefix"`

	MinIdle       int             `yaml:"min-idle"`
	MaxActive     int             `yaml:"max-active"`
	SingularTable bool            `yaml:"singular-table"`
	SlowThreshold int             `yaml:"slow-threshold"`
	LogLevel      logger.LogLevel `yaml:"log-level"`
}

type RedisConfig struct {
	Enable   bool   `yaml:"enable"`
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	Password string `yaml:"password"`
}

// 读取配置文件 app.yaml
func ConfigParse(appConfig *string) (*Config, error) {
	config := &Config{}
	file, err := os.Open(*appConfig)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	if err := yaml.NewDecoder(file).Decode(&config); err != nil {
		return nil, err
	}

	return config, nil
}
